package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.vo.PageVO;
import com.lcf.system.dao.GoodsCategoryDao;
import com.lcf.system.dto.GoodsCategoryDTO;
import com.lcf.system.entity.GoodsCategory;
import com.lcf.system.query.GoodsCategoryPageQuery;
import com.lcf.system.service.GoodsCategoryService;
import com.lcf.system.vo.GoodsCategoryVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品分类(GoodsCategory)表服务实现类
 *
 * @author lcf
 * @since 2025-04-24 21:14:34
 */
@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl extends ServiceImpl<GoodsCategoryDao, GoodsCategory> implements GoodsCategoryService {

    @Override
    public boolean insert(GoodsCategoryDTO dto) {
        Db.lambdaQuery(GoodsCategory.class).eq(GoodsCategory::getName, dto.getName()).oneOpt().ifPresent(item -> {
            throw new RuntimeException("分类名称重复");
        });

        return BeanUtil.copyProperties(dto, GoodsCategory.class).insert();
    }

    @Override
    public boolean update(Long id, GoodsCategoryDTO dto) {
        Db.lambdaQuery(GoodsCategory.class)
                .ne(GoodsCategory::getId, id)
                .eq(GoodsCategory::getName, dto.getName())
                .oneOpt().ifPresent(item -> {
            throw new RuntimeException("分类名称重复");
        });

        GoodsCategory goodsCategory = BeanUtil.copyProperties(dto, GoodsCategory.class);
        goodsCategory.setId(id);
        return goodsCategory.updateById();
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public GoodsCategoryVO query(Long id) {
        GoodsCategory goodsCategory = getById(id);
        return BeanUtil.copyProperties(goodsCategory, GoodsCategoryVO.class);
    }

    @Override
    public PageVO<GoodsCategoryVO> page(GoodsCategoryPageQuery query) {
        Page<GoodsCategory> page = Db.lambdaQuery(GoodsCategory.class)
                .page(query.toPage());
        return new PageVO<>(page, GoodsCategoryVO.class);
    }

    @Override
    public List<GoodsCategoryVO> allList() {
        List<GoodsCategory> list = Db.lambdaQuery(GoodsCategory.class).list();
        return BeanUtil.copyToList(list, GoodsCategoryVO.class);
    }
}

